<?php

namespace App\Console\Commands\Mybank\Tools;

use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Model\MybankFuyouBillRecordModel;
use App\Kuafu\Pay\Model\PayStreamMappingModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Pay\Model\RefundStreamModel;
use App\Kuafu\Pay\Model\ShopPaymentModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;

class CheckFyFileMoneyDiffCommand extends Command
{
    protected $signature = 'mybank:tools:check-fy-file-money-diff';

    protected $description = '校验富友文件数据';

    public function handle()
    {
        $shopPaymentsCollection = ShopPaymentModel::query()
                                                  ->where('payChannel', PayStreamModel::PAY_CHANNEL_FY)
                                                  ->whereRaw("payConfig -> '$.reserved_fy_term_id' != ''")
                                                  ->get()
                                                  ->map(function (ShopPaymentModel $v) {
                                                      return $v->toArray() + jsonToArr($v->payConfig);
                                                  })
                                                  ->values();


        $prefix              = "fuyouBill";
        $fyWhiteMerchantList = [
            '0001000F5937721'
        ];

        $date = '20231224';

        $filePath     = "/{$date}/08M0029877_{$date}.txt";
        $fileSystem   = getFileSystem();
        $realFilePath = getTmpDir($prefix . "/" . $filePath);

        $pathInfo = pathinfo($realFilePath);
        if (!$fileSystem->isDirectory($pathInfo["dirname"])) {
            $fileSystem->makeDirectory($pathInfo["dirname"], 0777, true);
        }
        $totalAll = 0;
        File::lines($realFilePath)->each(function ($line) use (
            $shopPaymentsCollection,
            $fyWhiteMerchantList,
            &$totalAll
        ) {
            if (empty($line)) {
                return;
            }
            list(
                $fyMerchantId,//商户号
                $cardNum,//卡号
                $cardAttr,//卡属性
                $referenceNum,//参考号
                $transactionType,//交易类型
                $terminalNum,//终端号
                $merchantOrderNo,//商户订单号
                $channelOrderNo,//渠道订单号
                $transactionAmount,//交易金额
                $transactionStatus,//交易状态
                $transactionStatusDesc,//交易状态说明
                $transactionCompletionTime,//交易完成时间
                $transactionDate,//交易日期
                $originalTransactionOrderNo,//原交易订单号
                $transactionFee,//交易手续费
                $externalOrderNo,//外部订单号
                $transactionCode,//交易代码
                $isPreferentialRate,//是否优惠费率
                $merchantDiscountRate,//商户扣率
                $errorTransactionSign,//差错交易标识
                $remark//备注
                ) = explode("|", $line);

            // 校验商户号是否在白名单里
            if (!in_array($fyMerchantId, $fyWhiteMerchantList)) {
                return true;
            }


            if (empty($originalTransactionOrderNo)) {
                // shopId 根据订单支付流水表重新去查
                $payInfo = PayStreamMappingModel::where('payNo', $merchantOrderNo)
                                                ->select(['shopId', 'payNo', 'bizId'])
                                                ->first();
            } else {
                $payInfo = RefundStreamModel::query()->where('refundNo', $merchantOrderNo)
                                            ->select(['shopId', 'refundNo as payNo', 'orderId as bizId'])
                                            ->first();
            }

            $shopId    = $payInfo->shopId;
            $kfOrderNo = $payInfo->bizId;

            if ($shopId != 15105) {
                // 判断终端号是否存在
                if (!$terminalNum) {
                    dd($line);
                    return true;
                }

            }


            $transactionAmount = bcmul100($transactionAmount);


            // 判断是否退款
            if (empty($originalTransactionOrderNo)) {
                $totalAll += $transactionAmount;
            } else {
                $totalAll -= $transactionAmount;
            }

        });

        dd($totalAll);

    }

}
